<template>
    <div>
        <div class="upload-option-wrap">
            <div class="upload-wraper">
                <input
                    ref="fileInput"
                    type="file"
                    accept="image/*"
                    @change="openHandle"
                />
                <div class="upload-img" v-if="uploadFileItem">
                    <img :src="uploadFileItem"/>
                    <div class="upload-img-mask"><span @click="openHandle">重新上传</span></div>
                </div>
                <div class="upload-btn-wrap" @click="openHandle" v-else>
                    <i class="iconfont icon-shangchuan"></i><span>点击上传</span>
                </div>
            </div>
            <div>
                <div class="tip">{{tip}}</div>
                <div v-if="uploadFileItem">
                    <el-button class="btn"
                        type="default"
                        @click="clearFormItem">删除</el-button>
                </div>
            </div>
        </div>
        <!-- 上传附件 -->
        <!-- <file-item isImg :fileItem="uploadFileItem" @update-file="updateFile"></file-item> -->
        <!-- 素材库 -->
        <material v-model:value="addVisible"
            :subCategory="data.subCategory"
            :list-type="1"
            :category="data.fileTypes"
            :limit="limitLength"
            :limitSize="fileSize"
            @on-ok="fileInsert" />
    </div>
</template>

<script setup>
// import FileItem from './file-item.vue';
import Material from '@/components/material/index.vue';
import { ref, reactive, computed, onMounted, watch, defineEmits, defineProps, defineExpose} from 'vue'
import { sizeFormat } from '@/lib/tools.js';

defineExpose({
    clearFormItem
})

const emit = defineEmits(['update:fileItem']);

const props = defineProps({
    checkConfig: { // 文件校验要求，来自模板
        type: Object,
        default: () => {
            return {}
        }
    },
    fileItem: { // 文件
        type: String,
        default: ''
    },
    btnText: {
        type: String,
        default: '选择图片'
    }
})

// 素材库是否显示
const addVisible = ref(false);

const uploadFileItem = ref(''); // 上传的文件

const isFirstUpload = ref(true);

const data = reactive({
    fileTypes: ['img'],
    subCategory: ['jpg', 'jpeg', 'png']
})


watch(() => props.fileItem, (val) => {
    uploadFileItem.value = val || '';
}, {deep: true})

onMounted(() => {
    uploadFileItem.value = props.fileItem || '';
})

// 校验规则
const rules = computed(() => {
    if(props.checkConfig.checkType === 'multifile') { // 多个
        const arr = props.checkConfig.checkRuleDTOS || [];
        let temp = {};
        arr.length > 0 && arr.forEach(item => {
            if (item.checkType === 'length') {
                temp.limitLength = Number(item.checkValue);
            } else if (item.checkType === 'fileTypes') {
                temp[item.checkType] = item.checkValue.split(',');
            } else {
                temp[item.checkType] = item.checkValue;
            }
        })
        return temp;
    } else if (props.checkConfig.checkType === 'fileSize') { // 文件大小
        return { fileSize: props.checkConfig.checkValue };
    } else if (props.checkConfig.checkType === 'length') { // 长度
        return { limitLength: Number(props.checkConfig.checkValue) };
    } else {
        return {};
    }
})

// 最多上传多少个文件
const limitLength = 1;

// 上传最大容量
const fileSize = computed(() => { // 规定后台返回的单位是M,素材库是byte，默认1M
    return rules.value && rules.value.fileSize && Number(rules.value.fileSize) * 1024 * 1024 || 1 * 1024 * 1024;
});

const tip = computed(() => {
    if (props.checkConfig.tips) {
        return props.checkConfig.tips;
    } else {
        let type = rules.value && rules.value.fileTypes && rules.value.fileTypes.join('，');
        let size = sizeFormat(fileSize.value);
        let content = type && `支持格式：${type}；` || '';
        return `${content}大小不能超过${size}`
    }
});



// 已经选择的文件
// const checkedfileItem = computed(() => {
//     let file = uploadFileItem.value.map(item=>item.materialId);
//     return file.length && JSON.parse(JSON.stringify(file)) || [];
// });

// 打开素材库
function openHandle() {
    // data.fileTypes = ['img'];
    // data.subCategory = rules.value && rules.value.fileTypes || ['jpg', 'jpeg', 'png'];
    addVisible.value = true;
    
}

// 选择文件
function fileInsert(fileItem) {
    if (!fileItem[0]) {
        return;
    }
    fileItem.forEach(item => {
        uploadFileItem.value = item.materialUrl;
    })
    emit('update:fileItem', uploadFileItem.value);
}

// 修改文件
function updateFile(val){
    uploadFileItem.value = JSON.parse(JSON.stringify(val));
    emit('update:fileItem', val);
}

// 清空文件
function clearFormItem () {
    uploadFileItem.value = '';
    emit('update:fileItem', '');
}


</script>

<style lang="scss" scoped>
.upload-option-wrap {
    display: flex;
    .upload-wraper{
      display: flex;
      align-items: center;
    }
    .upload-img{
        width: 70px;
        height: 70px;
        display: inline-block;
        overflow: hidden;
        border: 1px solid #E4E7ED;
        border-radius: 4px;
        position: relative;
        user-select: none;

        img{
            width: 100%;
            height: 100%;
            // width: 100%;
            // height: auto;
            // object-fit: contain;
            // object-position: center;
        }

        &:hover{
          .upload-img-mask{
              display: block;
          }
        }
    }
    .upload-img-mask{
        text-align: center;
        position: absolute;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        line-height: 70px;
        background: #00000065;
        transition: all 0.2s;
        display: none;
        cursor: pointer;
        span{
          font-size:12px;
          color:#ffffff;
        }
        &.upload-img-btn{
            flex-direction: column;
            align-items: center;
            justify-content: center;
            line-height: auto !important;
        }
        .span-upload{
            line-height: 14px;
            margin-top: 4px;
        }
        i{
            color:#ffffff;
            line-height: 1;
        }
    }
    .upload-btn-wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 70px;
        height: 70px;
        background: #F5F6F9;
        border-radius: 4px;
        cursor: pointer;
        user-select: none;
        border: 1px dashed #E2E6ED;
        justify-content: center;
        span{
            height: 14px;
            font-size: 12px;
            transform: scale(0.83);
            display: inline-block;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #1F6FFF;
            line-height: 14px;
            margin-top:4px;
        }
        i{
            color:#949BAF;
            line-height: 1;
        }
    }
    .upload-tips {
        height: 17px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
        line-height: 17px;
        display: inline-block;
        margin-left: 8px;
    }

    input[type="file"] {
      display: none;
    }
    .upload-img-default{
        width: 70px;
        height: 70px;
        background: #E8EAFD;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        position: relative;
        .span-name{
            font-size: 20px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: bold;
            color: #5254A9;
            line-height: 28px; 
        }

        &.color-1{
            background: #E8EAFD;
            .span-name{
                color: #5254A9;;
            }
        }
        &.color-2{
            background: #FCF0DD;
            .span-name{
                color: #8D5C2C;
            }
        }
        &.color-3{
            background: #DFF0F8;
            .span-name{
                color: #597DA4;;
            }
        }
        &.color-4{
            background: #E7F6D9;
            .span-name{
                color: #6A9F57;;
            }
        }

        &:hover{
          .upload-img-mask{
             display: flex;
          }
        }
    }
    .btn {
        margin-left: 20px;
        min-height:30px !important;
        padding: 8px 12px;
        border-radius: 2px;
        border: 1px solid var(--color-primary);
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: var(--color-primary);
        line-height: 14px;
    }
    .tip{
        height: 17px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: var( --main-text-tip);
        line-height: 17px;
        display: inline-block;
        margin-left: 20px;
    }
}
</style>